﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using WeiXin.Sdk.Domain;
using WeiXin.Sdk.Domain.Messages;
using WeiXin.Sdk.Common;

namespace WeiXinService.Controllers
{

    /// <summary>
    /// 
    /// </summary>
    public class WeiXinController : WeiXinBaseController
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(WeiXinController));

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }


        /// <summary>
        ///<![CDATA[接收微信通知]]>
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> Notify()
        {
            try
            {
                #region 1、GET请求，验证签名
                if (Request.HttpMethod.ToUpper() == "GET")
                {            //1.1、验证签名
                    if (CheckSignature(Request.QueryString["nonce"],
                                       Request.QueryString["timestamp"],
                                       Request.QueryString["signature"]))
                    {
                        return Content(Request.QueryString["echostr"]);
                    }
                    return Content("签名无效！");
                }
                #endregion 1、GET请求，验证签名

                #region 2、处理微信通知消息
                WeiXin.Sdk.Common.Serialization.XmlSerializer xmlSerializer = new WeiXin.Sdk.Common.Serialization.XmlSerializer(typeof(Message));
                string strInput = null;
                using (StreamReader reader = new StreamReader(Request.InputStream))
                {
                    strInput = await reader.ReadToEndAsync();
                }
                strInput = ClearXmlHeader(strInput);
                var recieve = (Message)xmlSerializer.Deserialize(strInput);

                //2.1、事件消息
                if (recieve.MsgType == WeiXin.Sdk.Common.Constants.SystemConstants.MSG_TYPE.EVENT)//事件消息
                {
                    switch (recieve.Event)
                    {
                        //2.1.1、扫描
                        case WeiXin.Sdk.Common.Constants.SystemConstants.EVENT.SCAN:
                            {
                                TextMessage textMessage = new WeiXin.Sdk.Domain.Messages.TextMessage()
                                {
                                    ToUserName = recieve.FromUserName,
                                    FromUserName = recieve.ToUserName,
                                    CreateTime = WeiXin.Sdk.Common.Util.GetUnixTime(),
                                    Content = $"欢迎关注！{recieve.EventKey}",
                                };

                                return Content(Serialize(textMessage), "text/xml");//推送消息
                            }
                        //2.1.2、关注事件
                        case WeiXin.Sdk.Common.Constants.SystemConstants.EVENT.SUBSCRIBE:
                            {
                                logger.Info($"关注事件 {recieve.EventKey}");
                                WeiXin.Sdk.Domain.Messages.TextMessage textMessage = new WeiXin.Sdk.Domain.Messages.TextMessage()
                                {
                                    ToUserName = recieve.FromUserName,
                                    FromUserName = recieve.ToUserName,
                                    CreateTime = WeiXin.Sdk.Common.Util.GetUnixTime(),
                                    Content = $"欢迎关考拉网！{recieve.EventKey}",
                                };
                                return Content(Serialize(textMessage), "text/xml");//推送消息
                            }
                        //2.1.3、取消关注事件
                        case WeiXin.Sdk.Common.Constants.SystemConstants.EVENT.UNSUBSCRIBE:
                            {
                                return Content("");
                            }
                        //2.1.4、菜单点击事件
                        case WeiXin.Sdk.Common.Constants.SystemConstants.EVENT.CLICK:
                            {
                                return Content("");
                            }
                        //2.1.5、菜单点击链接事件
                        case WeiXin.Sdk.Common.Constants.SystemConstants.EVENT.VIEW:
                            {
                                return Content("");
                            }
                        //2.1.6、地理定位
                        case WeiXin.Sdk.Common.Constants.SystemConstants.EVENT.LOCATION:
                            {
                                return Content("");
                            }
                    }
                }
                //2.2、接收消息
                else
                {
                    switch (recieve.MsgType)
                    {
                        //2.2.1、文本消息
                        case WeiXin.Sdk.Common.Constants.SystemConstants.MSG_TYPE.TEXT:
                            {

                            }
                            break;
                        //2.2.2、图片消息
                        case WeiXin.Sdk.Common.Constants.SystemConstants.MSG_TYPE.IMAGE:
                            {

                            }
                            break;
                    }
                }
                return Content("");
                #endregion 2、处理微信通知消息

            }
            catch (Exception ex)
            {
                logger.Error("接收微信通知时发生异常！", ex);
            }
            return new EmptyResult();
        }

        #region 私有方法
        /// <summary>
        /// <![CDATA[验证签名]]>
        /// </summary>
        /// <param name="nonce"></param>
        /// <param name="timestamp"></param>
        /// <param name="signature"></param>
        /// <returns></returns>
        private bool CheckSignature(string nonce, string timestamp, string signature)
        {
            if (string.IsNullOrEmpty(nonce) ||
                string.IsNullOrEmpty(timestamp) ||
                string.IsNullOrEmpty(signature)) return false;

            string strToken = System.Configuration.ConfigurationManager.AppSettings["Token"];//验证Token
            string[] strParameters = new string[] { strToken, timestamp, nonce };//把参数放到数组
            Array.Sort(strParameters);//加密/校验流程1、数组排序
            string strSignature = WeiXin.Sdk.Common.Security.Sha1.Encrypt(string.Join(string.Empty, strParameters));
            signature = signature.ToUpper();//大写
            return (strSignature == signature);
        }
        #endregion 
    }
}